package com.coffee.middleware.dict;


import com.coffee.core.CoffeeResponse;
import com.coffee.core.CoffeeResponseEnum;
import com.coffee.middleware.dict.cache.EnumDictCacheManager;
import com.coffee.middleware.dict.entity.DictDataDTO;
import com.coffee.middleware.dict.service.CoffeeDictRedisServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * @author Songkui
 * @since 2024-04-29
 */
@Tag(name = "字典缓存管理")
@Slf4j
@RestController
@RequestMapping("/coffee/dict-cache")
@AllArgsConstructor
public class DictCacheEndpoint {

    private final CoffeeDictRedisServiceImpl coffeeDictRedisService;

    @Operation(summary = "获取所有字典-登录成功调用")
    @GetMapping
    public CoffeeResponse<Map<String, Map<String, String>>> mapAll(){
        Map<String, Map<String, String>> map = EnumDictCacheManager.getInstance().mapAll();
        Map<String, List<DictDataDTO>> mapData = coffeeDictRedisService.mapByAll();
        for (Map.Entry<String, List<DictDataDTO>> entry : mapData.entrySet()){
            map.put(entry.getKey(), entry.getValue().stream().collect(Collectors.toMap(d -> String.valueOf(d.getDictCode()), DictDataDTO::getDictName)));
        }
        return CoffeeResponse.responseSuccess(map);
    }


    @Operation(summary = "刷新单个字典缓存")
    @GetMapping("/refresh/{typeId}")
    public CoffeeResponse<?> refreshByTypeId(@PathVariable("typeId") Integer typeId){
        coffeeDictRedisService.refreshByTypeId(typeId);
        return CoffeeResponse.response(CoffeeResponseEnum.Success);
    }

    @Operation(summary = "刷新所有字典缓存")
    @GetMapping("/refresh/all")
    public CoffeeResponse<?> refreshAll(){
        coffeeDictRedisService.refreshAll();
        return CoffeeResponse.response(CoffeeResponseEnum.Success);
    }


}
